<template>
  <PlusPage
    ref="plusPageInstance"
    :columns="pageConfig"
    :table="{ adaptive: true, hasIndexColumn: true, actionBar: { buttons, width: 180 } }"
    :default-page-info="{ pageSize: DEFAULT_PAGE_SIZE, page: 1 }"
    :request="getList"
  >
    <template #table-title>
      <el-row class="button-row">
        <el-button type="primary" :icon="Plus" @click="handleCreate">添加角色</el-button>
      </el-row>
    </template>
  </PlusPage>
  <!-- 弹窗新增or编辑 -->
  <PlusDialogForm
    v-model:visible="pageState.formVisible"
    v-model="pageState.form"
    :form="{ columns: pageConfig, rules: pageState.rules, labelWidth: 100 }"
    :dialog="{
      title: dialogTitle + '用户',
      width: '540px',
      top: '12vh',
      confirmLoading: pageState.confirmLoading,
    }"
    @confirm="handleSubmit"
    @cancel="handleCancel"
    @close="handleCancel"
  />
  <!-- 分配菜单 -->
  <el-dialog v-model="pageState.assignDialogVisible" title="修改授权" width="600">
    <assign-menu
      v-if="pageState.assignDialogVisible"
      :role-id="selectedRoleId"
      @cancel="handleCancelAssign"
    />
  </el-dialog>
</template>

<script lang="ts" setup>
import type { ButtonsCallBackParams, PageInfo, PlusColumn, PlusPageInstance } from '@wlydfe/pro-ui'
import type { BasePageReq } from '@wlydfe/service'
import type { RoleModel } from '@/api/type'
import { Plus } from '@element-plus/icons-vue'
import { useTable } from '@wlydfe/pro-ui'
import { omit } from 'lodash-es'
import { ref } from 'vue'
import { systemApi } from '@/api'
import AssignMenu from './assign-menu.vue'

//#region  -----------默认数据源及状态-----------

const plusPageInstance = ref<PlusPageInstance | null>(null)

const initFormData: Partial<RoleModel> = {
  name: '',
  desc: '',
}

const pageState = ref({
  formVisible: false,
  assignDialogVisible: false,
  isCreate: true, // 是否是新增
  confirmLoading: false,
  form: { ...initFormData },
  rules: {
    name: [
      {
        required: true,
        message: '请输入账号',
        trigger: 'blur',
      },
      {
        max: 10,
        message: '请输入6~10之间的字符',
        trigger: 'blur',
      },
    ],
  },
})

const dialogTitle = computed(() => (pageState.value.isCreate ? '新增' : '编辑'))

//#endregion

//#region  -----------页面配置-----------

const pageConfig: PlusColumn[] = [
  {
    label: '角色名称',
    prop: 'name',
    hideInSearch: false,
  },
  {
    label: '角色描述',
    prop: 'desc',
    valueType: 'textarea',
    tableColumnProps: {
      showOverflowTooltip: true,
    },
    maxWidth: 180,
  },
  {
    label: '创建时间',
    prop: 'createTime',
    hideInForm: true,
  },
  {
    label: '创建人',
    prop: 'creator',
    hideInForm: true,
  },
]

//#endregion

//#region  -----------操作按钮及配置-----------

const selectedRoleId = ref<string>('')

const { buttons } = useTable()
buttons.value = [
  {
    text: '修改',
    code: 'update',
    props: { type: 'primary' },
    onClick: async (params: ButtonsCallBackParams) => {
      // 根据业务需求，需要将指定字段赋值给表单
      pageState.value.form = { ...params.row }
      pageState.value.isCreate = false
      pageState.value.formVisible = true
    },
  },
  {
    text: '授权',
    code: 'auth',
    props: { type: 'primary' },
    onClick: async (params: ButtonsCallBackParams) => {
      selectedRoleId.value = params.row.roleId
      pageState.value.assignDialogVisible = true
    },
  },
  {
    text: '删除',
    code: 'delete',
    props: { type: 'danger' },
    confirm: {
      title: '提示',
      message: '确定删除该角色吗？',
      options: {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      },
    },
    onConfirm: async (params: ButtonsCallBackParams) => {
      await systemApi.deleteRole(params.row.roleId, { sysType: '31' })
      ElMessage.success('删除成功')
      refreshPage()
    },
  },
]

// 创建
const handleCreate = (): void => {
  pageState.value.form = { ...initFormData }
  pageState.value.isCreate = true
  pageState.value.formVisible = true
}

// 提交表单成功
const handleSubmit = async () => {
  const params = { ...pageState.value.form, sysType: '31' }

  pageState.value.confirmLoading = true
  const { succeed } = await systemApi.addOrEditRole(pageState.value.isCreate, params)
  pageState.value.confirmLoading = false
  if (succeed) {
    ElMessage.success(pageState.value.isCreate ? '创建成功' : '更新成功')
    handleCancel()
    refreshPage()
  }
}

// 表单取消
const handleCancel = () => {
  pageState.value.formVisible = false
  pageState.value.isCreate = true
}

// 刷新表格
const refreshPage = () => {
  plusPageInstance.value?.getList()
}

// 取消分配菜单
const handleCancelAssign = () => {
  pageState.value.assignDialogVisible = false
}

//#endregion

//#region  -----------接口请求及参数-----------
const DEFAULT_PAGE_SIZE = 20

const queryParams = ref<BasePageReq<Partial<RoleModel>>>({
  currentPage: 1,
  pageLength: DEFAULT_PAGE_SIZE,
  countTotal: true,
  filterModel: {},
})

const getList = async (query: Partial<PageInfo> & Partial<RoleModel>) => {
  // 构造查询参数
  queryParams.value.currentPage = query.page ?? 1
  queryParams.value.pageLength = query.pageSize ?? DEFAULT_PAGE_SIZE
  let roleName = ''
  if (query.name) {
    roleName = query.name
  }
  queryParams.value.filterModel = {
    ...omit(query, ['page', 'pageSize', 'value']),
    sysType: '31',
    roleName,
  }

  const { succeed, model, total } = await systemApi.getRolePage(queryParams.value)
  return {
    data: succeed ? model : [],
    total: total ?? 0,
  }
}
//#endregion
</script>
